//
//  NSDate+YCXTimeDescription.m
//  AnYiXing
//
//  Created by 马佳 on 2017/7/26.
//  Copyright © 2017年 云车问. All rights reserved.
//

#import "NSDate+YCXTimeDescription.h"
#define D_MINUTE    60
#define D_HOUR        3600
#define D_DAY        86400
#define D_DAY48     172800
#define D_WEEK        604800
#define D_MONTH     2592000
#define D_YEAR        31536000
@implementation NSDate (YCXTimeDescription)


#pragma mark 传时间+时间格式 -> 时间戳
+(NSString *)getTimestampWithDateTime:(NSString *)dateTime dateFormat:(NSString *)dateFormat{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = dateFormat; // 根据实际情况调整日期时间格式

    NSDate *date = [dateFormatter dateFromString:dateTime]; // 将字符串转换为日期

    // 获取时间戳
    NSTimeInterval timestamp = [date timeIntervalSince1970];
    NSString *timestampSt = [NSString stringWithFormat:@"%ld",(NSInteger)timestamp];
    return timestampSt;
}


#pragma mark 传14位时间 -> 返回时间戳 10位
+(NSString *)currentTimestamp:(NSString *)time
{
    if(time.length>0)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        
        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
        
        [formatter setTimeZone:timeZone];
        
        NSDate* date = [formatter dateFromString:time];
        
        long timeSp = [[NSNumber numberWithLong:[date timeIntervalSince1970]] longValue];
        NSString * currentTime = [NSString stringWithFormat:@"%ld",timeSp];
        
        return currentTime;
    }
    return nil;
}


#pragma mark 传14位时间 -> 返回几分钟前/几小时前/几天前/几周前/几年前
+(NSString *)processingTime:(NSString *)time{
    
    if(time.length>0)
    {
            long long timeSp = [[NSDate currentTimestamp:time] longLongValue];
        
            NSDate * currentdate =[NSDate date];
        
            long long currentTimeSp = [[NSNumber numberWithLong:[currentdate timeIntervalSince1970]] longLongValue];
        
            long long subTimeSp = currentTimeSp - timeSp;
            if(subTimeSp < D_HOUR)
            {
                
                long long time = subTimeSp/D_MINUTE;
                if(time == 0)
                {
                    time = 1;
                }
                return [NSString stringWithFormat:@"%lld分钟前",time];
            }else if(subTimeSp>=D_HOUR&&subTimeSp<D_DAY)
            {
                return [NSString stringWithFormat:@"%lld小时前",subTimeSp/D_HOUR];
                
            }else if(subTimeSp>=D_DAY&&subTimeSp<D_WEEK)
            {
                return [NSString stringWithFormat:@"%lld天前",subTimeSp/D_DAY];
                
            }else if(subTimeSp>=D_WEEK&&subTimeSp<D_MONTH)
            {
                return [NSString stringWithFormat:@"%lld周前",subTimeSp/D_WEEK];
            }else if(subTimeSp>=D_MONTH&&subTimeSp<D_YEAR)
            {
                return [NSString stringWithFormat:@"%lld月前",subTimeSp/D_MONTH];
            }else if(subTimeSp>=D_YEAR)
            {
                return [NSString stringWithFormat:@"%lld年前",subTimeSp/D_YEAR];
            }
    }
    return nil;
}


#pragma mark 传14位时间 -> 相差天数
+(NSInteger)processingDayTime:(NSString *)time{
    
    if(time.length>0){
        long long timeSp = [[NSDate currentTimestamp:time] longLongValue];
        NSDate * currentdate =[NSDate date];
        long long currentTimeSp = [[NSNumber numberWithLong:[currentdate timeIntervalSince1970]] longLongValue];
        long long subTimeSp = currentTimeSp - timeSp;
        return subTimeSp/D_DAY;
    }
    return 0;
}


#pragma mark 传10/13位时间戳 -> 相差天数
+(NSInteger)differenceDaysFormTimestamp:(NSString *)timestamp{
    
    if(timestamp.length>0){
        long long timeSp = timestamp.longLongValue > 10000000000 ? [timestamp longLongValue]/1000 : timestamp.longLongValue;
        NSDate * currentdate =[NSDate date];
        long long currentTimeSp = [[NSNumber numberWithLong:[currentdate timeIntervalSince1970]] longLongValue];
        long long subTimeSp = currentTimeSp - timeSp;
        return subTimeSp/D_DAY;
    }
    return 0;
}



#pragma mark 传14位时间 + 时间格式 -> 指定格式的时间  2014-01-02  yyyy-MM-dd    yyyy-MM-dd HH:mm
+(NSString *)TimestampGetTime:(NSString *)time andDateFormat:(NSString *)dateformat
{
    
    NSString *Dtime = time.description;
    if(Dtime.length>0)
    {
        long long timeSp = [[NSDate currentTimestamp:Dtime] longLongValue];
        
        NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:timeSp];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        
        [formatter setDateFormat:dateformat];
        
        NSString*timeString=[formatter stringFromDate:date];
        
        return timeString;
    }
    return nil;
}


#pragma mark 传10/13位时间戳 + 时间格式 -> 指定格式的时间
+ (NSString *)timeWithYearMonthDayCountDown:(NSString *)timestamp andDateFormat:(NSString *)dateformat{
    // 时间戳转日期
    
    // 传入的时间戳timeStr如果是精确到毫秒的记得要/1000
    NSTimeInterval timeInterval = timestamp.doubleValue > 10000000000 ? [timestamp doubleValue]/1000 : timestamp.doubleValue;
    NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 实例化一个NSDateFormatter对象，设定时间格式，这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:dateformat];
    NSString *dateStr = [dateFormatter stringFromDate:detailDate];

    return dateStr;
}


#pragma mark 判断传10/13位时间戳 -> 是否为当天,昨天,年月日
+ (NSString *)timeStringWithTimestamp:(NSString *)timestamp{
    
    NSTimeInterval timeInterval = timestamp.doubleValue > 10000000000 ? [timestamp doubleValue]/1000 : timestamp.doubleValue;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    if ([date isToday]) {//今天
        formatter.dateFormat = @"HH:mm";
        return [formatter stringFromDate:date];
    }else{//昨天
        if ([date isYesterday]) {
            formatter.dateFormat = @"昨天 HH:mm";
            return [formatter stringFromDate:date];
        }else{
            formatter.dateFormat = @"yyyy-MM-dd HH:mm";
            return [formatter stringFromDate:date];
        }
    }
    return nil;
}



//是否为今天
- (BOOL)isToday{
    //now: 2015-09-05 11:23:00
    //self 调用这个方法的对象本身
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear ;
    
    //1.获得当前时间的 年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
    
    //2.获得self
    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
    
    return (selfCmps.year == nowCmps.year) && (selfCmps.month == nowCmps.month) && (selfCmps.day == nowCmps.day);
}
//是否为昨天
- (BOOL)isYesterday{
    //2014-05-01
    NSDate *nowDate = [[NSDate date] dateWithYMD];
    
    //2014-04-30
    NSDate *selfDate = [self dateWithYMD];
    
    //获得nowDate和selfDate的差距
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *cmps = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0];
    
    return cmps.day == 1;
}


//是否在同一周
- (BOOL)isSameWeek{
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitWeekday | NSCalendarUnitMonth | NSCalendarUnitYear ;
    
    //1.获得当前时间的 年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
    
    //2.获得self
    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
    
    return (selfCmps.year == nowCmps.year) && (selfCmps.month == nowCmps.month) && (selfCmps.day == nowCmps.day);
}
//根据日期求星期几
- (NSString *)weekdayStringFromDate{
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期天", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone: timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:self];
    return [weekdays objectAtIndex:theComponents.weekday];
}


//格式化
- (NSDate *)dateWithYMD
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString *selfStr = [fmt stringFromDate:self];
    return [fmt dateFromString:selfStr];
}



#pragma mark 获取当前年月日 -> 【固定格式yyyyMMdd】
+(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYYMMdd"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
//    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}



#pragma mark 获取当前时间，自定义格式
+(NSString*)getCurrentTimesByDateFormat:(NSString *)dateFormat{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dateFormat];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
//    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}


#pragma mark 获取当前时间戳  (以秒为单位）
+(NSString *)getNowTimeTimestamp{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    return timeSp;
}

+(NSString *)getNowTimeTimestamp2{

    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];

    NSTimeInterval a=[dat timeIntervalSince1970];

    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型

    return timeString;

}


#pragma mark 获取当前时间戳  (以毫秒秒为单位）13位时间戳
+(NSString *)getNowTimeTimestampWith13{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    
    return timeSp;
}


#pragma mark 传10位时间戳 -> 处理明天8点与服务器时间做差值
+(void)nextDayTimestamp:(long long)nowtimestamp andBlock:(void(^)(NSString * time))timeshowblock
{

        NSDate * date;
        if(nowtimestamp>0)
        {
           date = [NSDate dateWithTimeIntervalSince1970:nowtimestamp];
        }else
        {
           date = [NSDate date];
        }
        NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH"];
    
        NSDate *nextDayDate;
        NSString * nowTime = [dateFormatter stringFromDate:date];
        if([nowTime intValue]>=0&&[nowTime intValue]<8)
        {
            nextDayDate = date;
        }else
        {
            nextDayDate = [NSDate dateWithTimeInterval:24*60*60 sinceDate:date];
            
        }
    
        [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

        NSString * nextTime = [dateFormatter stringFromDate:nextDayDate];
        NSArray *  timeArr  = [nextTime componentsSeparatedByString:@" "];
        NSString * nextDayTime =[NSString stringWithFormat:@"%@ 08:00:00",timeArr[0]];
        
        NSDate * nextDate = [dateFormatter dateFromString:nextDayTime];
        
        
        NSCalendar *calendar = [NSCalendar currentCalendar];
        
        NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitWeekOfMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        
        NSDateComponents *cmps = [calendar components:unit fromDate:date toDate:nextDate options:0];
        NSLog(@"剩余%02ld天,%02ld小时%02ld分%02ld秒", cmps.day ,cmps.hour, cmps.minute,cmps.second);

    
        if(timeshowblock)
        {
            NSString * timeshowStr = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",cmps.hour,cmps.minute,cmps.second];
            timeshowblock(timeshowStr);
        }
        
    

}


#pragma mark  把秒转换成 HH:mm:ss
+(NSString *)timeFormatted:(int)totalSeconds{
    
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
    
}
#pragma mark  秒转化成 xxdays xxhours xxminutes
+(NSString *)timeDayHourMinuteFormatted:(int)totalSeconds
{
    
    int days = totalSeconds / 86400;
    int hours = (totalSeconds - days*86400) /3600;
    int minutes;
    int subtime = (totalSeconds-days*86400-hours*3600);
    minutes= subtime/60;

   
    return [NSString stringWithFormat:@"%02ddays %02dhours %02dminutes",days, hours, minutes];
    
}


#pragma mark  距离当前的时间间隔描述
- (NSString *)timeIntervalDescription{
    NSTimeInterval timeInterval = -[self timeIntervalSinceNow];
    if (timeInterval < D_MINUTE) {
        return [NSString stringWithFormat:@"%.f秒前", timeInterval];
    } else if (timeInterval < D_HOUR) {
        return [NSString stringWithFormat:@"%.f分钟前", timeInterval / 60];
    } else if (timeInterval < D_DAY) {
        return [NSString stringWithFormat:@"%.f小时前", timeInterval / 3600];
    }
    else if (timeInterval < D_DAY48) {//48小时内
        return @"昨天";
    }
    else{

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        
        return [dateFormatter stringFromDate:self];
    }
}

@end
